package cz.possoft.explorer.meta.builder;

import java.io.BufferedInputStream;
import java.util.Properties;

import cz.possoft.explorer.meta.DomainMetadata;
import cz.possoft.explorer.resolver.Resolver;
import cz.possoft.explorer.resolver.method.MethodResolverImpl;

/**
 * Initialize domain metadata from property file where key is name of the class to add into metadata.
 * Value is Resolver class for the class in key.<br>
 * Default location of property file with domain configuration is "conf/domain.properties" where conf should be in classpath.
 * Different value can specified by system property "domain.metadata.property.file" .
 * 
 * Note: This implementation is actually unused. Initialization from XML is better and more flexible then initialization from properties.
 * 
 * @author <a href="mailto:mposolda@gmail.com">Marek Posolda</a>
 * @version $Revision$
 */
public class PropertyDomainMetadataBuilderImpl implements DomainMetadataBuilder
{
   // Name of system property with path to domain metadata properties file
   private static final String PROPERTY_NAME = "domain.metadata.property.file";
   
   // Default value of property file if property PROPERTY_NAME is not specified in system properties.
   private static final String DEFAULT_PROPERTY_VALUE = "conf/domain.properties";
   
   private Properties properties;
      
   public DomainMetadata build() throws DomainMetadataException
   {
      try
      {
         DomainMetadata resultMetadata = new DomainMetadata();
      
         // Init resource bundle
         String path = System.getProperty(PROPERTY_NAME) != null ? System.getProperty(PROPERTY_NAME) : DEFAULT_PROPERTY_VALUE;
         properties = new Properties();           
         properties.load(new BufferedInputStream(Thread.currentThread().getContextClassLoader().getResourceAsStream(path)));
         
      
         // iterate over all properties from property files
         for (Object typeClassNameRef  : properties.keySet())
         {
            String typeClassName = (String)typeClassNameRef;
            // get resolver class name
            String resolverClassName = (String)properties.get(typeClassName);
         
            // load classes and create instance of Resolver
            Class<?> typeClass = Class.forName(typeClassName);
            Class<? extends Resolver<?,?>> resolverClass = (Class<? extends Resolver<?,?>>)Class.forName(resolverClassName); 
            Resolver resolver = resolverClass.newInstance();
         
            // TODO: we don't know the type of typeClass :-( Maybe it is possible to do it more type-safe. It needs investigation.
            resultMetadata.addClassWithAllSupertypes(typeClass, resolver, null, new MethodResolverImpl());
         }
         
         return resultMetadata;
      }
      catch (Exception e)
      {
         throw new DomainMetadataException(e);
      }
   }
   

}

